package com.common.utils;


import com.alibaba.fastjson.JSONObject;
import com.common.convert.Convert;
import org.apache.commons.collections.MapUtils;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class MapUtil {
	
	public static String map2Str(Map<String, Object> map){
		return map2Str(map, false);
	}
	
	public static String map2Str(Map<String, Object> map, Boolean ignoreEmpty){
		StringBuffer buffer = new StringBuffer();
		if (map != null && !map.isEmpty()) {
			boolean first = true;
			for (Entry<String, Object> entry : map.entrySet()) {
				if (StringUtil.isBlank(Convert.asString(entry.getValue()))) {
					continue;
				}
				if (first) {
					first = false;
				}else {
					buffer.append("&");
				}
				if (entry.getValue() instanceof List) {
					buffer.append(entry.getKey()).append("=").append(JSONObject.toJSONString(entry.getValue()).replaceAll("=", ":"));
				}else {					
					buffer.append(entry.getKey()).append("=").append(entry.getValue());
				}
			}
		}
		return buffer.toString();
	}

	public static Map<String, Object> sort(Map<String, Object> map){
		if (MapUtils.isNotEmpty(map)){
			Map<String, Object> treeMap = new TreeMap<String, Object>();
			treeMap.putAll(map);
			return treeMap;
		}else {
			return null;
		}
	}
}
